# -*- coding: utf-8 -*-
import json
from abc import ABC

from datetime import datetime

from app.configs import kj236_pool
from app.views import CommonHandler
from app.tools.utils import dt2str, foot_point, distance, THRESHOLD


class CarHandler(CommonHandler, ABC):
    async def get(self):
        vehicles, items = {}, kj236_pool.select("SELECT *  from m_vehicle")
        for item in items:
            vehicles[item[1]] = item

        cars, items = [], kj236_pool.select("SELECT *  from m_car")
        for item in items:
            car = {
                "id": item[0],
                "carcode": item[1],
                "name": item[2],
                "type": int(item[4]),
                "inminetime": dt2str(item[6]),
                "intime": dt2str(item[7]),
                "readerid": item[9],
                "outtime": dt2str(item[12]),
                "dir": item[16],
                "distance": item[17],
                "regname": item[20],
                "speed": item[25],
                "mileage": 0,
                "water_temp": 0,
                "ch4_conc": 0,
                "surface_temp": 0,
                "exhaust_temp": 0,
                "rpm": 0,
                "battery": 0
            }

            if car["carcode"] in vehicles:
                vehicle = vehicles[car["carcode"]]
                car["mileage"] = vehicle[26]

                # 默认认为3秒以内的数据算有效
                if vehicle[34] is not None:
                    seconds = (datetime.now() - vehicle[34]).seconds
                    if seconds < 3:
                        car["speed"] = round(vehicle[25] / 3.6, 2)
                        car["water_temp"] = vehicle[28]
                        car["ch4_conc"] = vehicle[29]
                        car["surface_temp"] = vehicle[30]
                        car["exhaust_temp"] = vehicle[31]
                        car["rpm"] = vehicle[33]
                        car["battery"] = vehicle[34]

            cars.append(car)

        await self.response(data=cars)


class CarTrackHandler(CommonHandler, ABC):
    async def get(self):
        # car_id为空时全部获取
        time = self.get_argument("time", None)
        car_id = self.get_argument("car_id", None)
        if car_id is None and time is None:
            cars, items = [], kj236_pool.select("SELECT * FROM m_car_track")
            for item in items:
                car = {
                    "id": item[0],
                    "type": item[1],
                    "car_id": item[2],
                    "start_time": dt2str(item[3]),
                    "end_time": dt2str(item[4]),
                    "car_name": item[5],
                    "coordinates": item[6],
                }
                cars.append(car)
            await self.response(data=cars)
            return

        # car_id存在时,根据car_id进行过滤
        query = """
            SELECT * FROM m_car_track WHERE car_id='%s' AND end_time > '%s' AND start_time < '%s';
        """ % (car_id, time, time)
        cars, items = [], kj236_pool.select(query)
        for item in items:
            car = {
                "id": item[0],
                "type": item[1],
                "car_id": item[2],
                "start_time": dt2str(item[3]),
                "end_time": dt2str(item[4]),
                "car_name": item[5],
                "coordinates": item[6],
            }
            cars.append(car)
        await self.response(data=cars)

    async def post(self):
        params = self.json_params()
        car_id, car_name = params["car_id"], params["car_name"]
        start_time, end_time = params["start_time"], params["end_time"]
        coordinates, readers = params["coordinates"], []

        # 判断一下在coordinates范围内有那些分站
        items = kj236_pool.select("SELECT * from m_position_vehicle")
        for item in items:
            x, y = item[3], item[4]
            if x is None and y is None:
                continue
            for i in range(0, len(coordinates) - 1):
                ls, le, fp = coordinates[i], coordinates[i + 1], [0, 0]
                if foot_point([x, y], ls, le, fp):
                    if distance(x, y, fp[0], fp[1]) < THRESHOLD:
                        readers.append(item[1])
                        break
        query = """
            INSERT INTO m_car_track(type, car_id, start_time, end_time, car_name, coordinates, readers) 
            VALUES (%s, %s, %s, %s, %s, %s, %s)
        """
        values = ("vehicle", car_id, start_time, end_time, car_name, json.dumps(coordinates), json.dumps(readers))
        kj236_pool.execute(query, values)
        await self.response()

    async def delete(self):
        params = self.json_params()
        kj236_pool.execute("DELETE FROM m_car_track WHERE id={}".format(params['id']))
        await self.response()
